﻿# -*- coding: utf-8 -*-
from django.template.loader import get_template
from django.template import Template, Context
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail
import django.forms
import pdb
import sys
import datetime

import aboutme.localization
import comments.models

class ContactMeForm(django.forms.Form):
    contactme_subject = django.forms.CharField(max_length=100)
    contactme_email = django.forms.EmailField(required=False)
    contactme_message = django.forms.CharField(widget=django.forms.Textarea)

class TagSearchForm(django.forms.Form):
    tag_search_tag = django.forms.ModelChoiceField(queryset=comments.models.Tag.objects.order_by('name'), empty_label="...")
    tag_search_show_links = django.forms.BooleanField(required=False)
    tag_search_show_posts = django.forms.BooleanField(required=False)

class CategorySearchForm(django.forms.Form):
    cat_search_cat = django.forms.ModelChoiceField(queryset=comments.models.Category.objects.order_by('name'), empty_label="...")
    cat_search_show_links = django.forms.BooleanField(required=False)
    cat_search_show_posts = django.forms.BooleanField(required=False)
    
class PageLoadError(Exception):
    def __init__(self, params, error):
        self.params = params
        self.params['error'] = error

def getresponse(request, page_lang):
    params = \
    {
     'page_lang': 'rus',
     'items_per_page': 10,
    }
    #language
    if page_lang in aboutme.localization.supported.keys():
        params['page_lang'] = page_lang
        params['text'] = aboutme.localization.getlang(page_lang)
    else: raise PageLoadError(params, 'не удалось определить язык страницы')
    
    return params
   
def root(request, page_lang='rus'):
    try:
        params = getresponse(request, page_lang)
        return render(request, 'aboutme/root.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/root.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})

def resume(request, page_lang):
    try:
        params = getresponse(request, page_lang)
        mybirthdate = datetime.datetime(1986, 4, 5)
        today = datetime.datetime.today()
        myage = today.year - mybirthdate.year

        if today.month < mybirthdate.month or (today.month == mybirthdate.month and today.day < mybirthdate.day):
            myage = myage - 1
        params['age'] = myage        
        params['contactme'] = ContactMeForm()
        return render(request, 'aboutme/resume.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/resume.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})

def getmetas(request, page_lang):
    def list_names(objs): 
        for o in objs: yield o.name
    params = getresponse(request, page_lang)
    params['cats'] = comments.models.Category.objects.order_by('name')
    params['tags'] = comments.models.Tag.objects.order_by('name')
    cat_search = CategorySearchForm(request.POST)
    tag_search = TagSearchForm(request.POST)
    params['cat_search'] = cat_search
    params['tag_search'] = tag_search
    return params

def tags_and_categories(request, page_lang):
    try:
        params = getmetas(request, page_lang)
        return render(request, 'aboutme/tags_and_categories.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/tags_and_categories.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})
        
def category(request, page_lang, catname=None):
    try:
        params = getmetas(request, page_lang)
        if catname == None:
            if params['cat_search'].is_valid():
                catname = params['cat_search'].cleaned_data['cat_search_cat'].name
            else:
                raise PageLoadError(params, 'не удалось определить название категории')
            
        search_all = True
        if params['cat_search'].is_valid() and (params['cat_search'].cleaned_data['cat_search_show_posts'] == False and params['cat_search'].cleaned_data['cat_search_show_links'] == False):
            search_all = False
        items = []
        if search_all or (params['cat_search'].is_valid() and params['cat_search'].cleaned_data['cat_search_show_posts'] == True):
            items += comments.models.Post.objects.filter(category=catname).filter(isPublic=True).filter(isModerated=True)
        if search_all or (params['cat_search'].is_valid() and params['cat_search'].cleaned_data['cat_search_show_links'] == True):
            items += comments.models.Link.objects.filter(category=catname).filter(isPublic=True).filter(isModerated=True)
        items.sort()
        params['items'] = items
        return render(request, 'aboutme/search_result.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/search_result.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})

def tag(request, page_lang, tagname=None):
    try:
        params = getmetas(request, page_lang)
        if tagname == None:
            if params['tag_search'].is_valid():
                tagname = params['tag_search'].cleaned_data['tag_search_tag'].name
            else:
                raise PageLoadError(params, 'не удалось определить название тега')
            
        search_all = True
        if params['tag_search'].is_valid() and (params['tag_search'].cleaned_data['tag_search_show_posts'] == False or params['tag_search'].cleaned_data['tag_search_show_links'] == False):
            search_all = False
        items = []
        if search_all or (params['tag_search'].is_valid() and params['tag_search'].cleaned_data['tag_search_show_posts'] == True):
            items += comments.models.Post.objects.filter(tags__name=tagname).filter(isPublic=True).filter(isModerated=True)
        if search_all or (params['tag_search'].is_valid() and params['tag_search'].cleaned_data['tag_search_show_links'] == True):
            items += comments.models.Link.objects.filter(tags__name=tagname).filter(isPublic=True).filter(isModerated=True)
        items.sort()
        params['items'] = items
        return render(request, 'aboutme/search_result.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/search_result.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})

def feed(request, page_lang):
    try:
        params = getmetas(request, page_lang)
        params['items'] = comments.models.Post.objects.order_by('created').filter(isPublic=True).filter(isModerated=True)
        return render(request, 'aboutme/search_result.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/search_result.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})

def links(request, page_lang):
    try:
        params = getmetas(request, page_lang)
        params['items'] = comments.models.Link.objects.order_by('created').filter(isPublic=True).filter(isModerated=True)
        return render(request, 'aboutme/search_result.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/search_result.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})
        
def contactme(request, page_lang):
    try:
        params = getresponse(request, page_lang)
        contactme = ContactMeForm(request.POST)
        if contactme.is_valid():
            send_mail(
                contactme.cleaned_data['contactme_subject'],
                contactme.cleaned_data['contactme_message'],
                contactme.cleaned_data.get('contactme_email', 'nomail@arsenmuk.ru'),
                ['arsen.mukuchyan@gmail.com'],
                fail_silently=True)
        return render(request, 'aboutme/thanks_for_contactme.html', params)
    except PageLoadError as err:
        return render(request, 'aboutme/resume.html', err.params)
    except:
        return render(request, 'aboutme/error.html', {})
